package com.itcm.skymail.auth.controller;

import com.itcm.common.constant.AuthServerConstant;
import com.itcm.common.exception.BizCodeEnum;
import com.itcm.common.utils.R;
import com.itcm.skymail.auth.feign.ThirdFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 描述:
 * 登录注册
 *
 * @author cm_fighting
 * @create 2020-11-04 4:21 下午
 */
@RestController
@RequestMapping("/sms")
@Slf4j
public class SmsController {

    @Autowired
    private ThirdFeignService thirdFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/send")
    public R sendSms(String phone) {
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60s内不发验证码了
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = (int) (Math.random() * 900000 + 100000) + "";
        String redisSaveCode = code + "_" + System.currentTimeMillis();
        log.info("生成的随机验证码是：{}", code);
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redisSaveCode, 10, TimeUnit.MINUTES);


        thirdFeignService.sendSms(phone, code);
        return R.ok();
    }
}
